import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import moment from "moment";
import uniq from 'lodash/uniq';
import { Modal, Row, Col, Form, Card, Input, Select, Icon, Button, message, DatePicker, Popconfirm} from "antd";
import MaintainPerson from '../../Form/MaintainPerson';
import PtathCuring from '../../Path/Components/PtathCuring';
import PathAdd from "../../Path/Components/PathAdd";
import PathChoose from "../../Path/Components/PathChoose";
import CuingList from "../../Path/Components/CuingList";
import styles from '../../Pbulic.less';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const { RangePicker } = DatePicker;

@connect(({ task, path, global }) => ({
  loading:task.loading,
  detaildata:task.detaildata,
  dictionaries:global.dictionaries,
  selectSource:global.selectSource,
  pathcuring:path.pathcuring,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class TaskAdd extends PureComponent {
  constructor(props) {
    super(props);
    this.state={
      maintenanceSateId:null,
      removeIds:[],
      devChoose:[],
      pathChoose:[],
      modalPathChooseVisible: false,
      modalCuringChooseVisible: false,
      modalPathAddVisible: false,
    }
  }

  componentDidMount() {
    const { dispatch, match } = this.props;
    const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;
    // 维保单位列表
    dispatch({
      type: 'global/fetch_select_maintencompany',
    });

    // dispatch({
    //   type: 'global/fetch_select_maintenman',
    // });

    if (detailId!==0) {
        // 编辑时 读取详情
        dispatch({
          type: "task/fetch_task_info",
          payload: {
            taskId: detailId
          }
        })
          .then(() => {
            //根据维保id，获取相关人员
            const deptId = this.props.detaildata.maintenanceId;
            this.props.dispatch({
              type: 'global/fetch_select_maintenman',
              payload: {
                deptId,
                userType:"02",
              }
            })
          })
          .then(()=>{
          this.setState({
            maintenanceSateId:this.props.detaildata.maintenanceId,
          })
        });
    }
  }


  // 维保单位关联人搜索事件-------------------------------------
  handleSearchMaintain = ( value, oldvalue ) =>{
    const { dispatch } = this.props;
    const maintenanceId=value.maintenanceId;
    const userId=value.userId;
    const loadData=value.loadData;

    if(value.maintenanceId != oldvalue.maintenanceId){
      dispatch({
        type: "path/fetch_curing_clear",
      })
    }


    if(userId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_maintenman',
      })
    }

    if(loadData && maintenanceId!==0){
      this.handleChageMaintenance(maintenanceId);
      dispatch({
        type: 'global/fetch_select_maintenman',
        payload: {
          deptId:maintenanceId,
        },
      })
    }




  }
  checkMaintain =  (rule, value, callback) => {
    if (value.userId!==0) {
      callback();
      return;
    }
    callback('请选择维保单位及相关人员');
  }


  handleFormSubmit(e)  {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch, pathcuring, match } = this.props;
        const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;
        const taskId = detailId!=0 ? detailId : undefined
        const action = detailId ? 'edit' : 'add';

        const devIds = pathcuring && pathcuring.length > 0 ? uniq(pathcuring.map(item=>item.devId)) : undefined

        if(!devIds){
          message.error("请先选择路线和养护点");
          return false;
        }

        if(values.taskTime){
          values.beginTime = values.taskTime[0].unix() * 1000;
          values.endTime = values.taskTime[1].unix() * 1000;
        }


        if(values.maintenanceInfo && values.maintenanceInfo.maintenanceId!==0 && values.maintenanceInfo.userId!=0){
          values.maintenanceId = values.maintenanceInfo.maintenanceId;
          values.maintainManId = values.maintenanceInfo.userId;
        }


        dispatch({
          type: `task/${action}_task`,
          payload: {
            ...values,
            devIds,
            taskId,
            // devIds:pathcuring.map(e=>e.devId).join(",")
            maintenanceInfo:undefined,
            taskTime:undefined,
          }
        })
          .then(() => {
            this.handleReset();
            message.success(detailId === 0 ? "任务已添加成功" : "任务已修改成功");
            this.goBack();
          });
      }
    });
  }

  goBack = () => {
    const { dispatch, location, match } = this.props;
    const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;
    if(detailId===0){
      router.push({ pathname:`/maintain/task/list`});
    }else{
      router.push({ pathname:`/maintain/task/list`,  query: { ...location.query} });
    }
  }

  handleReset = () => {
    const { match } = this.props;
    this.setState({
      maintenanceSateId:match.params.id ? this.state.maintenanceSateId : null,
      removeIds:[],
      devChoose:[],
      pathChoose:[],
      modalPathChooseVisible: false,
      modalCuringChooseVisible: false,
      modalPathAddVisible: false,
    })
    this.props.form.resetFields();
  };

  // 维保单位切换时，更新state
  handleChageMaintenance = (value) => {
    this.setState({
      maintenanceSateId:value,
    })
  }

  // 显示选择唯一维保单位路线弹窗
  handlePathChooseModalVisible= flag => {
    const { dispatch } = this.props;
    dispatch({
      type: `path/fetch_data_clear`,
    }).then(()=>{
      this.setState({
        modalPathChooseVisible: !!flag,
      });
    })
  };

  // 显示选养护点弹窗
  handleCuringChooseModalVisible= flag => {
    const { dispatch } = this.props;
    dispatch({
      type: `path/fetch_data_clear`,
    }).then(()=>{
      this.setState({
        modalCuringChooseVisible: !!flag,
      });
    })

  };


  // 添加养护路线
  handleSubmitPathChoose = (e) => {
    e.preventDefault();
    const { dispatch } = this.props;
    const { pathChoose } = this.state;
    if (pathChoose && pathChoose.length>0) {
      dispatch({
        type: `path/fetch_path_equipment_merge`,
        payload: {
          lineIds: pathChoose
        }
      }).then(()=>{
        this.handlePathChooseModalVisible()
      })
    }
  }

  // 表格选中路线值，通过路线获取养护点
  handleSelectPathIds = (pathChoose) =>{
    this.setState({
      pathChoose:pathChoose,
    })
  }

  // 添加养护点
  handleSubmitCruingChoose = items =>{
    const { dispatch } = this.props;
    const { devChoose } = this.state;
    if (devChoose && devChoose.length>0) {
      dispatch({
        type: `path/fetch_curingupdate_add`,
        payload: devChoose
      }).then(()=>{
        this.handleCuringChooseModalVisible();
      })
    }
  }

  // 表格选中设备值，放到本页
  handleSelectCruing = items =>{
    this.setState({
      devChoose:items,
    })
  }


  // 删除选中的节点
  handleSelectRemove = items =>{
    this.setState({
      removeIds:items,
    })
  }

  handleRemoveCuring = () =>{
    const { dispatch } = this.props;
    const { removeIds } = this.state;
    if (removeIds && removeIds.length>0) {
      dispatch({
        type: `path/fetch_curingupdate_del`,
        payload: removeIds
      })
    }
  }


  // 显示新增修改model
  handlePathModalVisible= flag => {
    this.setState({
      modalPathAddVisible: !!flag,
    });
  };

  // 设备新增、编辑后model回调
  handlePathModelCallBack=()=>{
    this.handlePathModalVisible(false);
  }


  render() {
    const { match, detaildata, selectSource, pathcuring,loading } = this.props;
    const { maintenanceSateId, modalPathChooseVisible, modalCuringChooseVisible, modalPathAddVisible, removeIds } = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 }
    };

    const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;

    console.log('pathcuring',pathcuring);

    return (
     <Fragment>
      <Row gutter={{ md: 8, lg: 24, xl: 48 }} >
        <Col md={8} sm={24} className={styles.small_card}>
          <Card title={"任务信息"}
                extra={
                  <div >
                    <Button  type="primary"
                             disabled={pathcuring.length>0 ? false : true}
                             onClick={(e)=>this.handleFormSubmit(e)}
                             loading={loading.model_submit}
                    >
                      { detailId ? '编辑' : '提交'}
                    </Button>
                  </div>
                }
          >
            <Form layout="horizontal">
              <Row gutter={24}>
                {/*
                 <Col span={24}>
                  <FormItem {...formItemLayout} label="任务编号" colon={false}>
                    {getFieldDecorator("taskCode", {
                      initialValue: detailId === 0 ? undefined : detaildata.taskCode,
                      rules: [
                        // { required: true, message: "请输入设备名称" },
                      ]
                    })(
                      <Input placeholder="请输入任务编号" />
                    )}
                  </FormItem>
                 </Col>
                */}


                <Col span={24}>
                  <FormItem {...formItemLayout} label="任务名称" colon={false}>
                    {getFieldDecorator("taskName", {
                      initialValue: detailId === 0 ? undefined : detaildata.taskName,
                      rules: [
                        { required: true, message: "请输入任务名称" },
                      ]
                    })(
                      <Input placeholder="请输入任务名称" />
                    )}
                  </FormItem>
                </Col>
                <Col span={24}>
                  <FormItem  {...formItemLayout} label="执行时间" colon={false}>
                    {getFieldDecorator('taskTime',{
                      initialValue: detailId === 0 ? undefined
                        : (detaildata.beginTime && detaildata.endTime ? [moment(Number(detaildata.beginTime)),moment(Number(detaildata.endTime))] : []),
                      rules: [
                        { required: true, message: "请选择执行时间" },
                      ]
                    })(
                      <RangePicker
                        // showTime={{ format: 'HH:mm:ss' }}
                        format="YYYY-MM-DD"
                        placeholder={['开始时间', '结束时间']}
                      />
                    )}
                  </FormItem>
                </Col>


                <Col span={24}>
                  <FormItem {...formItemLayout} label="维保单位" colon={false}>
                    {getFieldDecorator("maintenanceInfo", {
                      initialValue: detailId === 0 ? {maintenanceId:0,userId:0} : {maintenanceId:detaildata.maintenanceId,userId:detaildata.maintainManId},
                      rules: [{required: true, message: "请选择维保单位及相关人员"},{validator: this.checkMaintain}],
                    })(
                      <MaintainPerson
                        span={24}
                        Mplaceholder={"请选择路线或养护点"}
                        placeholder={"请选择养护人"}
                        maintainData={selectSource.maintenance}
                        personnelData={selectSource.maintenman}
                        onChange={this.handleSearchMaintain}
                      />
                    )}
                  </FormItem>
                </Col>



                <Col span={24}>
                  <FormItem {...formItemLayout} label="备注" colon={false}>
                    {getFieldDecorator("remarks", {
                      initialValue: detailId === 0 ? undefined : detaildata.remarks,
                      rules: [{ max: 500, message: "不超过500个字" }]
                    })(
                      <TextArea
                        placeholder="请输入备注内容"
                        autosize={{ minRows: 3, maxRows: 6 }}
                      />
                    )}
                  </FormItem>
                </Col>

              </Row>
            </Form>

          </Card>
        </Col>
        <Col md={16} sm={24}  className={styles.small_card}>
          <Card
            title={"任务路线设置"}
            bodyStyle={{padding:1}}
            extra={
              <div >
                <Button  type="primary"
                         style={{marginRight:15}}
                         disabled={maintenanceSateId ? false : true}
                         onClick={this.handlePathChooseModalVisible}
                >
                  添加养护路线
                </Button>
                <Button  type="primary"
                         style={{marginRight:15}}
                         disabled={maintenanceSateId ? false : true}
                         onClick={this.handleCuringChooseModalVisible}
                >
                  添加养护点
                </Button>
                <Button  type="primary"
                         style={{marginRight:15}}
                         disabled={pathcuring.length>0 ? false : true}
                         onClick={this.handlePathModalVisible}
                >
                  保存为新路线
                </Button>
                <Popconfirm title={<span>是否确定要删除?<br/>删除后需点击编辑后生效</span>}  onClick={this.handleRemoveCuring} okText="是" cancelText="否">
                <Button  type="danger"
                         disabled={removeIds.length>0 ? false : true}
                >
                  删除
                </Button>
                </Popconfirm>
              </div>
            }
          >
            {
              (detailId === 0 ? maintenanceSateId : detaildata.maintenanceId) &&
              <PtathCuring
                // detailInfoId={detailInfoId}
                // doDel={doDel}
                selectCallBack={this.handleSelectRemove}
                refreshStop={this.handleUpdateDelOver}
                tableData={pathcuring}
                // loading={loadingdev}
              />
            }
            {
              !(detailId === 0 ? maintenanceSateId : detaildata.maintenanceId) &&
              <div style={{textAlign:'center',padding:30,color:'rgba(0, 0, 0, 0.45)'}}>请先选择维保单位</div>
            }

          </Card>
        </Col>



      </Row>


       <Modal
         title={"添加养护路线"}
         visible={modalPathChooseVisible}
         onOk={this.handleSubmitPathChoose}
         onCancel={() => this.handlePathChooseModalVisible(false)}
         width={900}
         destroyOnClose={true}
         bodyStyle={{padding:0}}

       >
         <PathChoose
           maintenanceId={maintenanceSateId}
           selectCallBack={this.handleSelectPathIds}
         />
       </Modal>

       <Modal
         title={"添加养护点"}
         visible={modalCuringChooseVisible}
         onOk={this.handleSubmitCruingChoose}
         onCancel={() => this.handleCuringChooseModalVisible(false)}
         width={900}
         destroyOnClose={true}
         bodyStyle={{padding:0}}
       >
         <CuingList
           maintenanceId={maintenanceSateId}
           // doAdd={doAdd}
           selectCallBack={this.handleSelectCruing}
           // refreshStop={this.handleUpdateAddOver}
         />
       </Modal>

       <PathAdd
         visible={modalPathAddVisible}
         onCancel={e => this.handlePathModalVisible(e)}
         callback={this.handlePathModelCallBack}
         maintenanceId={maintenanceSateId}
         detailId={0}
         devIds={pathcuring && pathcuring.length>0 && pathcuring.map(item=>item.devId)}
         // // dictionaries={dictionaries}
         // selectSource={selectSource}
       />
     </Fragment>
    );
  }
}
